# !/usr/bin/env Python3
# -*- coding: utf-8 -*-
# 作者   : 王宗龙
# 文件     : user.py
# 时间     : 2020/12/9 15:30
# 开发工具 : PyCharm

from typing import Union
from apps.base.base import *
import hashlib
import time
import jwt
from apps.models import Users,AccessRecords,Loginhistory
from apps.base.db import Newsession
from fastapi import Header, HTTPException,Request,APIRouter,Body,Depends
import time,datetime
from pydantic import BaseModel
route = APIRouter()

def md5value(s):
    md5 = hashlib.md5()
    md5.update(s)
    return md5.hexdigest()

@logger.catch()
@route.post("/login",summary='用户登录，账号密码交换TOKEN')
def login(request:Request,username: str=Body(...), password: str=Body(...),):
    '''TOKEN 获取接口
    ============================
    '''
    logger.debug(username)
    session = Newsession()
    user= session.query(Users).filter_by(name=username,passwd=md5value(password.encode())).first()
    logger.debug(user)
    resout=False
    hisuser = Loginhistory(username=username,fromip=request.client.host)
    if user:
        logger.info(user)
        user.lastlogin = datetime.datetime.now()
        session.commit()
        info={"id":user.id,"username":user.name,"nicename":user.nicename,"Role":user.role}
        payload = {
            "iat": int(time.time()),
            "exp": int(time.time()) + 86400 * 7,
            # token签发者
            'iss': 'zlWang',
            'data': info,
            "jti": "4f1g23a12aa"
        }
        # 生成token
        token = jwt.encode(payload, conf.SECRET_KEY, algorithm='HS512', )
        data = Ok({"token": token,  "user": info})
        session.add(user)
        resout = True
        hisuser.nicename=user.nicename
    else:
        data = Fail('','登录失败!')
    hisuser.resout=resout
    session.add(hisuser)
    session.commit()
    return data

@logger.catch()
class User_info:
    def __init__(self,userid):
        self.USERID=userid

class CurrentUser:
    def __init__(self,request: Request ,Token: str = Header(None) ,QTOKEN: str=None):
        if Token or QTOKEN:
            tk=Token if Token else QTOKEN
            users = ''
            try:
                users = jwt.decode(tk, conf.SECRET_KEY, algorithms=['HS512'])
            except Exception as e:
                logger.error(e)
            if users:
                user = users['data']
                logger.debug(user)
                self.userid = user['id']
                self.username = user['username']
                self.nicename = user['nicename']
                self.role=user['Role']
                # logger.debug(conf.access_records)
                if conf.access_records:
                    accessrecords=AccessRecords(userid=user['id'],username=user['username'], nicename=user['nicename'],url=str(request.url),method=request.method,fromip=request.client.host)
                    # logger.debug(accessrecords.nicename)
                    session = Newsession()
                    session.add(accessrecords)
                    session.commit()
                return
        logger.debug("未登录")
        data = {"msg": "用户未登录!", "code": -1}
        raise HTTPException(status_code=200, detail=data)


@logger.catch()
@route.get("/userlist",summary='用户列表')
def getUser(searstr:str='',page :Page= Depends(Page),  user : CurrentUser= Depends(CurrentUser)):
    if user.role!='admin':
        return Fail('','权限不足')
    session = Newsession()
    user=session.query(Users).filter(Users.name.like(f'%{page.search}%')).limit(page.limit).offset(page.offset).all()
    ct=session.query(Users).count()
    data = Ok({"data": user,"total":ct})
    return data

class Postuser(BaseModel):
    id :Union[int ,None] = None
    name : str
    nicename : str
    role : str
    status : bool


@logger.catch()
@route.post("/useradd",summary='新增\修改用户',)
def addUser(zuser :Postuser=Body(),user : CurrentUser= Depends(CurrentUser)):
    if user.role!='admin':
        return Fail('','权限不足')
    session = Newsession()
    if zuser.id:
        us = session.query(Users).filter_by(id=zuser.id).first()
        if not us:
            return Fail('', '数据错误！')
        else:
            us.name=zuser.name
            us.nicename=zuser.nicename
            us.role=zuser.role
            us.status=zuser.status
            logger.info(us.status)
            session.commit()
            return Ok()
    else:
        us = session.query(Users).filter_by(name=zuser.name).first()
        if not us:
            us=Users(name=zuser.name,nicename=zuser.nicename,role=zuser.role,status=zuser.status,passwd='e10adc3949ba59abbe56e057f20f883e' )
            session.add(us)
            session.commit();
            session.flush();
            return Ok()
        else:
            return Fail('','用户已存在')



@logger.catch()
@route.get("/userdel",summary='删除用户',)
def delUser(ID: str,user : CurrentUser= Depends(CurrentUser)):
    if user.role!='admin':
        return Fail('','权限不足')
    session = Newsession()
    user = session.query(Users).filter_by(id=ID).first()
    if user:
        session.delete(user)
        session.commit();
        session.flush()
        return Ok()
    else:
        return Fail('','用户不存在')



@logger.catch()
@route.get("/accress",summary='访问记录')
def getAcc(searstr:str='',page :Page= Depends(Page),  user : CurrentUser= Depends(CurrentUser)):
    if user.role!='admin':
        return Fail('','权限不足')
    session = Newsession()
    data=session.query(AccessRecords).filter(Users.name.like(f'%{page.search}%')).limit(page.limit).offset(page.offset).all()
    ct=session.query(AccessRecords).count()
    return Ok({"data": data,"total":ct})

@logger.catch()
@route.get("/hisuser",summary='登录记录')
def gethisuser(page :Page= Depends(Page),  user : CurrentUser= Depends(CurrentUser)):
    if user.role!='admin':
        return Fail('','权限不足')
    session = Newsession()
    data=session.query(Loginhistory).filter(Users.name.like(f'%{page.search}%')).limit(page.limit).offset(page.offset).all()
    ct=session.query(Loginhistory).count()
    return Ok({"data": data,"total":ct})


@logger.catch()
@route.get("/resetpass",summary='密码重置')
def resetpass(ID: str,user : CurrentUser= Depends(CurrentUser)):
    if user.role != 'admin':
        return Fail('', '权限不足')
    session = Newsession()
    user = session.query(Users).filter_by(id=ID).first()
    if user:
        user.passwd='e10adc3949ba59abbe56e057f20f883e'
        session.commit();
        session.flush()
        return Ok()
    else:
        return Fail('', '用户不存在')


class Setpassword(BaseModel):
    oldpass : str
    password : str
    rpassword : str


@logger.catch()
@route.post("/changepass",summary='密码修改')
def changepass(passdata : Setpassword=Body(),user : CurrentUser= Depends(CurrentUser)):
    if passdata.password==passdata.rpassword:
        session = Newsession()
        cuser = session.query(Users).filter_by(id=user.userid).first()
        holdpasswd=md5value(passdata.oldpass.encode())
        if holdpasswd==cuser.passwd:
            cuser.passwd= md5value(passdata.password.encode())
            session.commit()
            return Ok()
        else:
            return Fail('', '原密码错误')
    else:
        return Fail('', '两次密码不一致')
    if user.role != 'admin':
        return Fail('', '权限不足')
